import { Rectangle } from "./rectangle.js";
import { birdDom, gameDom, landDom } from "./util.js";

const birdStyles = getComputedStyle(birdDom);
const birdWidth = parseFloat(birdStyles.width);
const birdHigth = parseFloat(birdStyles.height);
const birdTop = parseFloat(birdStyles.top);
const birdLeft = parseFloat(birdStyles.left);

export class Bird extends Rectangle {
    constructor() {
        super(birdWidth, birdHigth, birdLeft, birdTop, 0, 0, birdDom);
        this.g = 500 // 向下的加速度
        this.maxY = gameDom.clientHeight - this.height - landDom.clientHeight;
        this.timer = null;  // 定时器
        this.swingStauts = 1; // 翅膀状态
        this.render();  // 初始化
    }

    // 开始飞
    startSwing() {
        if (this.timer) return
        this.timer = setInterval(() => {
            this.swingStauts = (this.swingStauts + 1) % 3 + 1;
            this.render(); // 重新渲染
        }, 200);
    }

    // 重写渲染
    render() {
        super.render();
        this.dom.className = `bird swing${this.swingStauts}`; // 添加类名
    }

    // 停止飞
    stopSwing() {
        clearInterval(this.timer);
        this.timer = null;
    }

    // 小鸟落下移动
    move(duration) {
        super.move(duration);  // 先调用父类方法
        // 再通过自己改变速度
        this.yspeed += this.g * duration;
    }

    // 小鸟落下判断
    onMove() {
        if (this.top < 0) {
            this.top = 0;
        }
        if (this.top > this.maxY) {
            this.top = this.maxY;
        }
    }
    // 小鸟向上跳
    jump() {
        this.yspeed = -200;
    }
}